package com.dhh.sky.widget;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.dhh.sky.R;
import com.dhh.sky.util.CUtil;
import com.dhh.sky.util.Constant;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

public class CameraGridImageAdapter extends BaseAdapter {
	private LayoutInflater inflater;
	private SharedPreferences spTemp;
	private Context context;
	private List<String> keys = new ArrayList<String>();
	private Map valueMap = new HashMap();
	
	public CameraGridImageAdapter(Context context){
		this.context = context;
		inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		spTemp = context.getSharedPreferences(Constant.FOLDER_LOG_CAMERA_FOLDER_TEMP, 0);
		initData();
	}
	
	private void initData(){
		valueMap = spTemp.getAll();
		Iterator it = valueMap.keySet().iterator();
		while(it.hasNext()){
			keys.add(it.next().toString());
		}
	}
	
	@Override
	public int getCount() {
		return keys.size();
	}

	@Override
	public String getItem(int position) {
		return valueMap.get(keys.get(position)).toString();
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		final View view = convertView != null ? convertView : inflater.inflate(R.layout.item_camera_grid_image,parent,false);
		ImageView imageView = (ImageView) view.findViewById(R.id.image);
		String path = this.getItem(position);
		File file = new File(path);
		if(file.exists()){
			imageView.setImageBitmap(CUtil.decodeBitmap(file, 160, 160));
		}
		
		view.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				String key = keys.get(position);
				if(spTemp.contains(key)){
					spTemp.edit().remove(key).commit();
					view.findViewById(R.id.pli_selected).setVisibility(View.INVISIBLE);
				}else{
					spTemp.edit().putString(key, valueMap.get(key).toString()).commit();
					view.findViewById(R.id.pli_selected).setVisibility(View.VISIBLE);
				}
			}
		});
		
		return view;
	}
	
	private void removeItem(String key){
		valueMap.remove(key);
		keys.remove(key);
		this.notifyDataSetChanged();
		spTemp.edit().remove(key.toString()).commit();
	}
}
